package com.example.blogcommon.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.security.interfaces.RSAKey;
import java.util.concurrent.TimeUnit;

@Slf4j
public class Redis {
    public static String REDIS_DEFAULT_PREFIX = "default";

    public static String REDIS_SPLIT = ":";

    private StringRedisTemplate redisTemplate;

    public Redis(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    public String get(String key) {
        try {
            return key == null ? null : redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            log.error("get error, key {}", key);
            return null;
        }
    }

    public boolean hasKey(String key) {
        try {
            return key == null ? false : redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error("haskey error key{}",key);
            return false;
        }
    }

    public boolean set(String key, String value) {
        try {
            redisTemplate.opsForValue().set(key,value);
            return true;
        } catch (Exception e) {
            log.error("set error key {}",key);
            return false;
        }
    }

    public boolean set(String key, String value, long timeout) {
        try {
            if (timeout > 0) {
                redisTemplate.opsForValue().set(key,value, timeout, TimeUnit.SECONDS);
                return true;
            } else {
                return  set(key,value);
            }
        } catch (Exception e) {
            log.error("set error key {}",key);
            return false;
        }
    }

    public String buildKey(String prefix, String... args) {
        if (prefix == null) {
            prefix = REDIS_DEFAULT_PREFIX;
        }
        StringBuilder key = new StringBuilder();
        key.append(prefix);
        if (args != null) {
            for (String arg : args) {
                key.append(REDIS_SPLIT);
                key.append(arg);
            }
        }
        return key.toString();
    }
}
